package com.landiao.ctrler.weixin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.landiao.common.Constant;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.weixin.bean.WxMpPayOrderQuery;
import com.landiao.ctrler.BaseCtrler;
import com.landiao.service.PayFlowService;

/**
 * 功能说明:微信支付
 */
@Controller
@RequestMapping("/weixin")
public class WxPayCtrler extends BaseCtrler{
	
	@Autowired
	private PayFlowService payFlowService;
	
	/**
	 * 支付通知
	 * @param request
	 * @param response
	 */
	@RequestMapping("payNotify")
	public void payNotify(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			WxMpPayOrderQuery payOrder = WxMpPayOrderQuery.fromXml(request.getInputStream());
			log.debug(payOrder.toString());
			if (payOrder!=null&&Constant.WX_SUCCESS.equals(payOrder.getReturn_code())) {//支付通知
				if(payOrder.getOut_trade_no().indexOf(CodecUtils.RECHARGE_PRE)>=0){
					payFlowService.checkCzWxPayInfo(payOrder.getOut_trade_no(), payOrder);
				}else{
					payFlowService.checkXfWxPayInfo(payOrder.getOut_trade_no(), payOrder);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		String xml = "<xml>" +
		        "<return_code><![CDATA[SUCCESS]]></return_code>" +
		        "<return_msg><![CDATA[OK]]></return_msg>" +
		        "</xml>";
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(xml);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
